package com.dm.wallpaper.library.customview;

import com.dm.wallpaper.library.utils.Log;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.text.DecimalFormat;
import java.util.Optional;

public class PxUtil {
    private static Display display;

    public static Display getDisplay() {
        if (display == null) {
            throw new NullPointerException("请先初始化 PxUtil");
        }
        return display;
    }

    public static void initContext(Context context) {
        display = DisplayManager.getInstance().getDefaultDisplay(context).get();
    }

    public static int screenWidth() {
        return getDisplay().getAttributes().width;
    }

    public static int screenHeight() {
        return getDisplay().getAttributes().height;
    }

    public static float fp2px(float fp) {
        float sca = getDisplay().getAttributes().scalDensity;
        return (float) (fp * sca + (double)0.5 * (fp >= 0 ? 1 : -1));
    }

    public static float vp2px(float vp) {
        float dpi = getDisplay().getAttributes().densityPixels;
        return (float) (vp * dpi + (double)0.5 * (vp >= 0 ? 1 : -1));
    }


    public static PixelMap getPixelMap(Context context, int resourceId) {
        Resource resource = null;
        try {
            resource = context.getResourceManager().getResource(resourceId);
            PixelMap mBitmap = ImageSource.create(resource, new ImageSource.SourceOptions()).createPixelmap(null);
            return mBitmap;
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("Util.getPixelMap([view, resourceId]):89");
        }
        return null;

    }


    /**
     * 格式化数字(保留一位小数)
     *
     * @param num 数字
     * @return 格式化后的数字
     */
    public static String formatNum(int num) {
        DecimalFormat format = new DecimalFormat("0");
        return format.format(num);
    }

    /**
     * 格式化数字(保留两位小数)
     *
     * @param num 数字
     * @return 格式化后的数字
     */
    public static String formatNum(float num) {
        if (((int) num * 1000) == (int) (num * 1000)) {
            //如果是一个整数
            return String.valueOf((int) num);
        }
        DecimalFormat format = new DecimalFormat("0.00");
        return format.format(num);
    }
}
